package com.fooddelivery.Service.Impl;

import com.fooddelivery.Common.Execption.BusinessException;
import com.fooddelivery.Common.Execption.ErrorCode;
import com.fooddelivery.Entity.Dish;
import com.fooddelivery.Mapper.DishMapper;
import com.fooddelivery.Service.DishService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 * 菜品 服务实现类
 * </p>
 *
 * @author zhengruiyang
 * @since 2025-08-31
 */
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    private DishMapper dishMapper;

    public boolean updateAll(Dish dish){

        LocalDateTime now = LocalDateTime.now();
        dish.setUpdateTime(now);
        try {
            dishMapper.saveOrUpdate(dish);
        } catch (DataIntegrityViolationException e) {
            throw new BusinessException(ErrorCode.USER_ALREADY_EXISTS);
        }
        return true;
    }

    @Override
    public boolean updateStatus(Dish dish) {
         return dishMapper.updateStatus(dish);
    }

    @Override
    public boolean save(Dish dish) {
        if(dish.getCategoryId() == null || dish.getCategoryId() <= 0) {
            throw new BusinessException(ErrorCode.DISH_CATEGORY_NOT_NULL);
        }
        LocalDateTime now = LocalDateTime.now();
        dish.setCreateTime(now);
        dish.setUpdateTime(now);
//        if (dish.getUpdateUser() == null) {
//            dish.setUpdateUser(1L);
//        }
//        if (dish.getCreateUser() == null) {
//            dish.setCreateUser(1L);
//        }
        try {
            dishMapper.save(dish);
        } catch (DataIntegrityViolationException e) {
            throw new BusinessException(ErrorCode.USER_ALREADY_EXISTS);
        }
        return true;
    }

    @Override
    public int dishCount() {
        return  dishMapper.dishCount();
    }

}
